package com.zero.java.base.readFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

/**
 * @author Lenovo
 * 
 *         public final class Files extends Object 
 *         public static byte[] readAllBytes(Path path) throws IOException 
 *         public static List<String> readAllLines(Path path) throws IOException
 *         public static Path write(Path path,byte[] bytes,OpenOption... options) throws IOException
 *         public static InputStream newInputStream(Path path,OpenOption... options) throws IOException
 */
public class ReadFiles {

	private final static String file_name = "cfg/test.txt";
	private final static String file_name_02 = "cfg/words.txt";
	private final static String file_name_03 = "cfg/text.txt";

	public static void main(String[] args) throws IOException {

		// 读取文件
		Path path = Paths.get(file_name);
		byte[] readAllBytes = Files.readAllBytes(path);
		// 将文件以字符串的形式读入
		String inStr = new String(readAllBytes, StandardCharsets.UTF_8);
		System.out.println(inStr);

		//将文件行序列读入
		List<String> readAllLines = Files.readAllLines(path);
		System.out.println(readAllLines);
		
		//写出一个字符串到文件中
		Files.write(Paths.get(file_name_02),readAllBytes);
		
		//向指定文件中追加内容
		Files.write(Paths.get(file_name_02), readAllBytes,StandardOpenOption.APPEND);
		
		//读入文件
		InputStream in = Files.newInputStream(Paths.get(file_name_02));
		byte[] bytes = new byte[1024];
		//使用字节数组构建字符串
		int length = 0;
		//第一种
		/*while((length = in.read(bytes))!=-1){
			System.out.println(Arrays.toString(bytes));
		}*/
		//第二种
		/*while((length = in.read(bytes))!=-1){
			System.out.println(length);
			System.out.println(new String(bytes,0,length));
		}
		*/
		
		//写入文件
		OutputStream out = Files.newOutputStream(Paths.get(file_name_03));
		//写入文件
		while((length = in.read(bytes))!=-1){
			out.write(length);
			//out.write(bytes, 0, length);
		}
		//关闭流
		in.close();
		out.flush();
		out.close();
	}
}
